import Foundation
import CommonCrypto

// 腾讯地图API配置
let API_KEY = "L5OBZ-2SPON-MCNFK-S63PP-ZJWIV-CTBL4"
let SECRET_KEY = "52tEmYw2osLQnVGECy3GES7zivNlokWm"

// 测试坐标数据（4个海外 + 1个国内）
let testCoordinates = [
    // 海外坐标
    ("东京塔", 35.6586, 139.7454),      // 日本东京
    ("埃菲尔铁塔", 48.8584, 2.2945),    // 法国巴黎
    ("自由女神像", 40.6892, -74.0445),  // 美国纽约
    ("悉尼歌剧院", -33.8568, 151.2153), // 澳大利亚悉尼
    // 国内坐标
    ("北京天安门", 39.9087, 116.3975)   // 中国北京
]

// MD5扩展
extension Data {
    func md5() -> Data {
        let length = Int(CC_MD5_DIGEST_LENGTH)
        var digest = [UInt8](repeating: 0, count: length)
        _ = self.withUnsafeBytes { body in
            CC_MD5(body.baseAddress, CC_LONG(self.count), &digest)
        }
        return Data(digest)
    }
    func hexString() -> String {
        return self.map { String(format: "%02hhx", $0) }.joined()
    }
}

// 生成腾讯地图API签名
func generateTencentSig(path: String, params: [String: String], secretKey: String) -> String {
    // 1. 参数排序
    let sortedParams = params.sorted { $0.key < $1.key }
    // 2. 拼接参数串（未编码）
    let paramString = sortedParams.map { "\($0.key)=\($0.value)" }.joined(separator: "&")
    // 3. 拼接签名串
    let signString = "\(path)?\(paramString)\(secretKey)"
    // 4. MD5
    let md5 = signString.data(using: .utf8)!.md5().hexString()
    return md5
}

// 测试腾讯地图API（支持每秒限额5次）
func testTencentMapsAPI() async {
    print("=== 腾讯地图API测试（4个海外 + 1个国内） ===")
    print("时间: \(Date())")
    print("每秒限额: 5次")
    print()
    
    for (index, (locationName, lat, lng)) in testCoordinates.enumerated() {
        print("测试 \(index + 1)/\(testCoordinates.count): \(locationName) (\(lat), \(lng))")
        
        // 1. 构建原始参数（未编码）
        var params: [String: String] = [
            "key": API_KEY,
            "location": "\(lat),\(lng)",
            "get_poi": "1"
        ]
        // 2. 生成签名
        let sig = generateTencentSig(path: "/ws/geocoder/v1", params: params, secretKey: SECRET_KEY)
        params["sig"] = sig
        // 3. 构建URL（参数需编码，sig放最后）
        let encodedParams = params.map { "\($0.key)=\($0.value.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")" }
        let urlString = "https://apis.map.qq.com/ws/geocoder/v1?" + encodedParams.joined(separator: "&")
        guard let url = URL(string: urlString) else {
            print("❌ URL构建失败")
            continue
        }
        
        do {
            let (data, response) = try await URLSession.shared.data(from: url)
            if let httpResponse = response as? HTTPURLResponse {
                print("HTTP状态码: \(httpResponse.statusCode)")
            }
            
            // 解析JSON
            if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
               let status = json["status"] as? Int {
                if status == 0 {
                    if let result = json["result"] as? [String: Any],
                       let addressComponent = result["address_component"] as? [String: Any] {
                        let country = addressComponent["nation"] as? String ?? "未知"
                        let province = addressComponent["province"] as? String ?? "未知"
                        let city = addressComponent["city"] as? String ?? "未知"
                        let district = addressComponent["district"] as? String ?? "未知"
                        print("✅ 解析成功:")
                        print("  国家: \(country)")
                        print("  省份: \(province)")
                        print("  城市: \(city)")
                        print("  区县: \(district)")
                        if let formattedAddress = result["formatted_addresses"] as? [String: Any],
                           let recommend = formattedAddress["recommend"] as? String {
                            print("  推荐地址: \(recommend)")
                        }
                    }
                } else {
                    let message = json["message"] as? String ?? "未知错误"
                    print("❌ API错误: \(message)")
                }
            }
        } catch {
            print("❌ 网络请求失败: \(error)")
        }
        
        print("---")
        
        // 每秒限额5次，每次请求后等待200毫秒（5次/秒 = 200ms间隔）
        if index < testCoordinates.count - 1 {
            print("等待200毫秒...")
            try? await Task.sleep(nanoseconds: 200_000_000) // 200毫秒
        }
    }
    
    print("=== 测试完成 ===")
}

// 运行测试
Task {
    await testTencentMapsAPI()
}
RunLoop.main.run() 